package cn.com.youjile.server;

import cn.com.youjile.coding.GeneralDecoder;
import cn.com.youjile.coding.GeneralEncoder;
import cn.com.youjile.handler.GeneralServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Author youjile
 * @CreateDate 2021/3/12
 * @Describe server服务端
 */
public class GeneralServer extends Thread{

    private static final Logger logger = LoggerFactory.getLogger(GeneralServer.class);

    private CountDownLatch latch;       //控制线程
    private int heartBeatSencord;

    private int port;
    private static boolean is_open_heart = true;    //是否开启心跳功能，true开启，false不开启

    //所有活动的用户
    public static ChannelGroup allChannels = new DefaultChannelGroup(
            GlobalEventExecutor.INSTANCE);


    public GeneralServer(int heartBeatSencord, int port, CountDownLatch latch){
        this.port = port;
        this.latch = latch;
        this.heartBeatSencord = heartBeatSencord;
    }


    @Override
    public void run() {
        try {
            latch.await();  //等待创建本线程的父线程通知本线程继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("等待主线程执行完毕时异常！");
        }
        logger.info("开始初始化group server服务，port=[" + this.port + "]......");
        EventLoopGroup  bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        try {
            b.group(bossGroup,workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.handler(new LoggingHandler(LogLevel.INFO));
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception { //这里异常使用向上层抛出的方式处理，应该这里如果执行出错，程序就应该停止了
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("GeneralDecoder", new GeneralDecoder());
                    pipeline.addLast("GeneralEncoder",new GeneralEncoder());
                    /**
                     * 添加心跳
                     * 第一个参数：如果35s没有读到数据，就触发事件。（心跳事件应该比这个时间小，比如这里的心跳时间设置为30s）
                     * 第二个参数：如果40s没有写数据，就触发事件。(这里关乎心跳的响应，此时间应该比读心跳时间要大才合理)
                     * 第三个参数：如果60s没有读也没有写数据，就触发这个时间，这时候应该关闭这个链接了。
                     * 第四个参数：时间单位设置
                     */
                    if(is_open_heart) {
                        pipeline.addLast("HeartBeat", new IdleStateHandler(heartBeatSencord,heartBeatSencord+5,heartBeatSencord*2, TimeUnit.SECONDS));
                    }
                    pipeline.addLast(new GeneralServerHandler());
                }
            });
            //绑定端口，同步等待成功
            ChannelFuture f = b.bind(port).sync();
            //等待服务器监听端口关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void clear(){
        //断开所有的连接，并清理channel
        GeneralServer.allChannels.disconnect();  //断开所有连接
        GeneralServer.allChannels.close();       //关闭所有channel
        GeneralServer.allChannels.clear();       //所有活动的用户，清空容器
    }
}
